package edu.suda.cxtz.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import edu.suda.cxtz.modules.enums.DataScopeEnum;
import edu.suda.cxtz.modules.exception.BadRequestException;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.List;

public class SecurityUtils {

    public static UserDetails getCurrentUser() {
        UserDetailsService userDetailsService = SpringContextHolder.getBean(UserDetailsService.class);
        return userDetailsService.loadUserByUsername(getCurrentUsername());
    }

    public static String getCurrentUsername() {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication == null) {
            throw new BadRequestException(HttpStatus.UNAUTHORIZED, "登录过期");
        }
        System.out.println(authentication.getPrincipal());
        if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            return userDetails.getUsername();
        }
        throw new BadRequestException(HttpStatus.UNAUTHORIZED, "找不到当前登录信息");
    }

    /**
     * 获取系统用户ID
     * @return 系统用户ID
     */
    public static Long getCurrentUserId() {
        UserDetails userDetails = getCurrentUser();
        // 将 Java 对象转换为 JSONObject 对象
        JSONObject jsonObject = (JSONObject) com.alibaba.fastjson.JSON.toJSON(userDetails);
        return jsonObject.getJSONObject("user").getLong("id");
    }



    public static List<Long> getCurrentUserDataScope(){
        UserDetails userDetails = getCurrentUser();

        JSONObject jsonObject = (JSONObject) JSON.toJSON(userDetails);
        JSONArray jsonArray = jsonObject.getJSONArray("dataScopes");
        return JSON.parseArray(jsonArray.toJSONString(), Long.class);
    }

    public static String getDataScopeType() {
        List<Long> dataScopes = getCurrentUserDataScope();
        if(!dataScopes.isEmpty()) {
            return "";
        }
        return DataScopeEnum.ALL.getValue();
    }
}
